<template>
  <div class="page-mobile-authentication">
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="true"
      title="认证中心"
    ></white-header>
    <div class="user_info">
      <div class="info_item" @click="authInfoHandle('identity')">
        <div class="info_left">身份</div>
        <div class="info_right">
          <div>
            <span v-if="identityName">{{ identityName }}</span>
            <span v-else>请选择</span>
          </div>
          <img class="right_icon" src="/img/mobile/right-icon.png" alt="" />
        </div>
      </div>
      <div class="info_item" @click="authInfoHandle('hospital')">
        <div class="info_left">医院</div>
        <div class="info_right">
          <div>
            <span v-if="hospitalName">{{ hospitalName }}</span>
            <span v-else>请选择</span>
          </div>
          <img class="right_icon" src="/img/mobile/right-icon.png" alt="" />
        </div>
      </div>
      <div class="info_item" @click="authInfoHandle('department')">
        <div class="info_left">科室</div>
        <div class="info_right">
          <div>
            <span v-if="departmentName">{{ departmentName }}</span>
            <span v-else>请选择</span>
          </div>
          <img class="right_icon" src="/img/mobile/right-icon.png" alt="" />
        </div>
      </div>
      <div class="info_item" @click="authInfoHandle('professional')">
        <div class="info_left">职称</div>
        <div class="info_right">
          <div>
            <span v-if="professionalName">{{ professionalName }}</span>
            <span v-else>请选择</span>
          </div>
          <img class="right_icon" src="/img/mobile/right-icon.png" alt="" />
        </div>
      </div>
    </div>
    <van-popup v-model="professionalShowPicker" round position="bottom">
      <van-picker
        show-toolbar
        :columns="professionalList"
        @cancel="professionalShowPicker = false"
        @confirm="onProfessionalConfirm"
      />
    </van-popup>
    <van-popup v-model="identityShowPicker" round position="bottom">
      <van-picker
        show-toolbar
        :columns="identityColumns"
        @cancel="identityShowPicker = false"
        @confirm="onIdentityConfirm"
      />
    </van-popup>
    <div
      class="submit-btn"
      :class="[authentication.userId ? 'disabled' : '']"
      @click="handleSubmit"
    >
      提交
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import { userLogout } from "~/api/account/user";
import {
  getProfessionalList,
  getIdentityList,
  getHospitalList,
  getDepartmentList,
  getAuthUserInfo,
  setAuthUserInfo
} from "~/api/authentication";
const defaultAuthForm = {
  departmentId: null,
  hospitalId: null,
  identityId: null,
  professionalId: null
};
export default {
  props: ["setDisabled", "refreshFun", "setLoading"],
  components: {
    WhiteHeader
  },
  data() {
    return {
      // authentication: Object.assign({},defaultAuthForm),
      hospitalList: [], //医院列表
      departmentList: [], //科室列表
      professionalShowPicker: false, //是否展示职称下拉框
      professionalColumns: [], //职称列表
      identityShowPicker: false, //是否展示身份下拉框
      identityColumns: [], //身份列表
      columns: [
        { id: 1, text: "医生" },
        { id: 2, text: "护士" },
        { id: 3, text: "医技" },
        { id: 4, text: "药师" },
        { id: 5, text: "行政" },
        { id: 6, text: "其他" }
      ] //可以这样操作
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      token(state) {
        return state.token;
      },
      login_type(state) {
        return state.login_type;
      },
      authentication(state) {
        return state.authentication;
      },
      kl_md(state) {
        return state.kl_md;
      }
    }),
    //过滤职称列表
    professionalList() {
      if (this.authentication.identityId) {
        // return this.professionalColumns
        //   .map(item => {
        //     return { ...item, text: item.name };
        //   })
        //   .filter(item => item.identityId == this.authentication.identityId);
          return this.professionalColumns
          .map(item => {
            return { ...item, text: item.name };
          });
      } else {
        return [];
      }
    },
    //身份名称
    identityName() {
      let obj = this.identityColumns.find(
        item => item.id == this.authentication.identityId
      );
      if (obj) {
        return obj.name;
      } else {
        return null;
      }
    },
    //医院名称
    hospitalName() {
      let obj = this.hospitalList.find(
        item => item.id == this.authentication.hospitalId
      );
      if (obj) {
        return obj.name;
      } else {
        return null;
      }
    },
    //科室名称
    departmentName() {
      let obj = this.departmentList.find(
        item => item.id == this.authentication.departmentId
      );
      if (obj) {
        return obj.name;
      } else {
        return null;
      }
    },
    //职称名称
    professionalName() {
      let obj = this.professionalColumns.find(
        item => item.id == this.authentication.professionalId
      );
      if (obj) {
        return obj.name;
      } else {
        return null;
      }
    }
  },
  watch: {},
  activated() {
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/m/login");
      } else {
        console.log("路由", this.$route);
        this.initPage();
      }
    }
    this.setDisabled(false);
    this.refreshFun(() => {
      this.initPage();
      this.getAuthUserInfo();
      this.setLoading(false);
      this.SET_IS_LOADING(false);
    });
  },
  methods: {
    ...mapMutations([
      "SET_IS_LOADING",
      "SET_AUTHENTICATION",
      "UPDATE_AUTHENTICATION"
    ]),
    // 信息设置处理函数
    authInfoHandle(type) {
      if(this.authentication.userId){
        return;
      }
      if (type === "identity") {
        this.identityShowPicker = true;
      } else if (type === "hospital") {
        this.$router.push("/m/auth-detail?action=hospital");
      } else if (type === "department") {
        this.$router.push(
          "/m/auth-detail?action=department"
        );
        // this.$router.push(
        //   "/m/auth-detail?action=department&departmentId=" +
        //     this.authentication.identityId
        // );
      } else if (type === "professional") {
        this.professionalShowPicker = true;
      }
      return false;
    },
    //设置职称
    onProfessionalConfirm(value) {
      // this.authentication.professionalId = value.id;
      this.UPDATE_AUTHENTICATION({ professionalId: value.id });
      this.professionalShowPicker = false;
    },
    //设置身份
    onIdentityConfirm(value) {
      // this.authentication.identityId = value.id;
      this.UPDATE_AUTHENTICATION({
        identityId: value.id,
        // professionalId: null,
        // departmentId: null
      });
      this.identityShowPicker = false;
    },
    //提交认证信息
    async handleSubmit() {
      if (this.authentication.userId) {
        return false;
      } else {
        let obj = Object.assign({}, this.authentication);
        if (Object.values(obj).filter(item => item).length == 4) {
          let params = {
            userId: this.user_info.id,
            ...obj
          };
          let result = await setAuthUserInfo(params);
          if(result && result.data && result.data.code == 200){
            this.$toast("提交成功！");
            this.getAuthUserInfo();
          }else{
            this.$toast("提交失败！");
          }
          // console.log(params);
          // console.log("验证通过");
        } else {
          this.$toast("请填写完整信息！");
          // console.log("验证失败");
        }
      }
    },
    //获取身份列表
    async getIdentity() {
      this.SET_IS_LOADING(true);
      let result = await getIdentityList();
      if (result && result.data && result.data.code == 200) {
        this.identityColumns = result.data.data.rows.map(item => {
          return { ...item, text: item.name };
        });
      } else {
        this.$toast("网络波动，请稍后再试！");
      }
      this.SET_IS_LOADING(false);
    },
    //获取职称列表
    async getProfessional() {
      this.SET_IS_LOADING(true);
      let result = await getProfessionalList();
      if (result && result.data && result.data.code == 200) {
        this.professionalColumns = result.data.data.rows;
      } else {
        this.$toast("网络波动，请稍后再试！");
      }
      this.SET_IS_LOADING(false);
    },
    //获取医院列表
    async getHospital() {
      this.SET_IS_LOADING(true);
      let result = await getHospitalList();
      if (result && result.data && result.data.code == 200) {
        this.hospitalList = result.data.data.rows;
      } else {
        this.$toast("网络波动，请稍后再试！");
      }
      this.SET_IS_LOADING(false);
    },
    //获取科室列表
    async getDepartment() {
      this.SET_IS_LOADING(true);
      let result = await getDepartmentList();
      if (result && result.data && result.data.code == 200) {
        this.departmentList = result.data.data.rows;
      } else {
        this.$toast("网络波动，请稍后再试！");
      }
      this.SET_IS_LOADING(false);
    },
    //获取用户的认证信息
    async getAuthUserInfo() {
      this.SET_IS_LOADING(true);
      let result = await getAuthUserInfo(this.user_info.id);
      if (result && result.data && result.data.code == 200) {
        // this.departmentList = result.data.data.rows;
        console.log("用户认证信息", result.data.data);
        let obj = result.data.data;
        if (obj) {
          this.SET_AUTHENTICATION(obj);
        }
      } else {
        this.$toast("网络波动，请稍后再试！");
        this.logout();
        this.$router.replace("/m/login");
      }
      this.SET_IS_LOADING(false);
    },
    async logout(){
      let params = {};
      if (this.login_type == "email") {
        params = {
          email: this.user_info.email
        };
      } else if (this.login_type == "mobile") {
        params = {
          account: this.user_info.mobile
        };
      } else {
        params = {
          account: this.user_info.account
        };
      }
      let result = await userLogout(params);
      if (result.data.code === 200) {
        this.$store.commit("SIGN_OUT");
        this.$router.replace("/m/user");
        this.$toast(this.$t("locale.mobile.user.t18"));
      } else {
        this.$store.commit("SIGN_OUT");
        // this.$toast(this.$t("locale.mobile.user.t19"));
      }
    },
    initPage() {
      this.getIdentity();
      this.getProfessional();
      this.getHospital();
      this.getDepartment();
      console.log("初始化页面");
    }
  },
  created() {
    //初始化页面数据
    if (process.client) {
      if (!this.token && Object.keys(this.user_info).length == 0) {
        this.$router.replace("/m/login");
      } else {
        this.initPage();
        this.getAuthUserInfo();
      }
    }
    //下拉回调
    this.refreshFun(() => {
      this.initPage();
      this.getAuthUserInfo();
      this.setLoading(false);
      this.SET_IS_LOADING(false);
    });
  },
  mounted() {}
};
</script>

<style lang="scss" scoped>
.page-mobile-authentication {
  min-height: 100vh;
  background-color: #eef0f4;
  .submit-btn {
    width: 5.568rem;
    margin: 0.3rem auto 0.3rem;
    height: 0.768rem;
    line-height: 0.768rem;
    border-radius: 0.384rem;
    text-align: center;
    font-size: 0.3rem;
    font-weight: bold;
    background: var(--theme-color);
    color: #ffffff;
  }
  .submit-btn.disabled {
    cursor: not-allowed;
    opacity: 0.5;
  }
  .user_info {
    background: #ffffff;
    margin: 0.2rem 0;
    padding-left: 0.4rem;
    box-sizing: border-box;
    width: 100%;
    .info_item {
      width: 100%;
      height: 1rem;
      border-bottom: 0.0096rem solid #ededf1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 0.3rem;
      font-weight: bold;
      .info_left {
        font-size: 0.3rem;
        font-weight: bold;
      }
      .info_right {
        display: flex;
        align-items: center;
        color: #adafb3;
        .avater {
          width: 1.056rem;
          height: 1.056rem;
          overflow: hidden;
          border-radius: 50%;
          display: block;
        }
        .right_icon {
          margin: 0 0.1rem;
          width: 0.2304rem;
          height: 0.2304rem;
          display: block;
        }
      }
    }
    .info_item:last-child {
      border-bottom: none;
    }
  }
}
</style>
